<?php

class Dict
{
        private $source, $target;
        public function __construct() {}
        public function setSource($filename)
        {
                if (file_exists($filename)):
                        $this->source = $filename;
                else:
                        throw new Exception("File $filename does not exist");
                endif;
        }
        public function setTarget($filename)
        {
                $this->target = $filename;
        }
        public function createDictionary($section = '')
        {
                // Some error handling first
                if ($this->source == ''):
                        throw new Exception("Source is not set");
                        return false;
                endif;
                if ($this->target == ''):
                        throw new Exception("Target is not set");
                        return false;
                endif;

                // Parse ini file and check section (if necessary)
                $dict = @parse_ini_file($this->source, TRUE);

                // With section?
                if (trim($section) != ''):
                        // check first
                        if (!isset($dict[$section])):
                                throw new Exception("Section $section does not exists in dictionary $this->source");
                                return false;
                        endif;
                        $content = $dict[$section];
                else:
                        $content = $dict;
                endif;

                // Write javascript file
                $dictionary = sprintf("var DICT = %s;", json_encode($content));
                if (!$handle = fopen($this->target, 'w')):
                        throw new Exception("Target $this->source not writable");
                        return false;
                endif;
                if (!fwrite($handle, $dictionary)):
                        throw new Exception("Could not write to file $this->source");
                        return false;
                endif;
                fclose($handle);
        }

}

?>